from qiniu import Auth, put_file, BucketManager
from flask import current_app
import os

def get_qiniu_auth():
    """获取七牛云认证对象"""
    access_key = current_app.config['QINIU_ACCESS_KEY']
    secret_key = current_app.config['QINIU_SECRET_KEY']
    return Auth(access_key, secret_key)

def delete_from_qiniu(file_url):
    """从七牛云删除文件
    
    Args:
        file_url: 文件的完整URL
        
    Returns:
        bool: 删除是否成功
    """
    try:
        # 获取认证对象
        q = get_qiniu_auth()
        bucket = BucketManager(q)
        
        # 从URL中提取文件key
        domain = current_app.config['QINIU_DOMAIN']
        if not domain.startswith(('http://', 'https://')):
            domain = f'https://{domain}'
        key = file_url.replace(f'http://{domain}/', '').replace(f'https://{domain}/', '')
        
        # 删除文件
        ret, info = bucket.delete(current_app.config['QINIU_BUCKET_NAME'], key)
        
        if ret is None:
            return True
        return False
    except Exception as e:
        current_app.logger.error(f"删除七牛云文件失败: {str(e)}")
        return False

def upload_to_qiniu(local_file, remote_name):
    """上传文件到七牛云"""
    try:
        # 检查文件是否存在
        if not os.path.exists(local_file):
            raise FileNotFoundError(f"要上传的文件不存在: {local_file}")
            
        # 获取认证对象
        q = get_qiniu_auth()
        
        # 生成上传凭证
        token = q.upload_token(current_app.config['QINIU_BUCKET_NAME'], remote_name)
        
        # 上传文件
        ret, info = put_file(token, remote_name, local_file)
        
        current_app.logger.info(f"七牛云上传返回信息: ret={ret}, info={info}")
        
        if ret and ret.get('key'):
            # 直接返回文件的 key，不拼接域名
            return {
                'url': ret['key'],  # 只返回文件的 key
                'key': ret['key']
            }
        
        error_msg = f"上传失败: {info.error}" if info else "上传失败: 未知错误"
        current_app.logger.error(error_msg)
        raise Exception(error_msg)
        
    except Exception as e:
        current_app.logger.error(f"上传到七牛云失败: {str(e)}")
        raise

def verify_qiniu_config():
    """验证七牛云配置是否正确"""
    from flask import current_app
    
    try:
        required_configs = [
            'QINIU_ACCESS_KEY',
            'QINIU_SECRET_KEY',
            'QINIU_BUCKET_NAME',
            'QINIU_DOMAIN',
            'QINIU_REGION'
        ]
        
        # 检查应用上下文
        if not current_app:
            raise RuntimeError('必须在应用上下文中运行此函数')
        
        # 检查配置
        for config in required_configs:
            if not current_app.config.get(config):
                raise ValueError(f'缺少七牛云配置: {config}')
        
        auth = get_qiniu_auth()
        bucket = BucketManager(auth)
        
        # 获取所有bucket列表
        ret, info = bucket.buckets()
        current_app.logger.info(f'可用的 Bucket 列表: {ret}')
        
        if info.status_code != 200:
            current_app.logger.error(f'七牛云连接测试失败，状态码: {info.status_code}, 错误信息: {info.error}')
            raise Exception(f'七牛云连接测试失败: {info.error}')
        
        configured_bucket = current_app.config['QINIU_BUCKET_NAME']
        if configured_bucket not in ret:
            available_buckets = ', '.join(ret)
            raise Exception(
                f'配置的 Bucket "{configured_bucket}" 不存在。\n'
                f'可用的 Bucket 列表: {available_buckets}'
            )
        
        current_app.logger.info(f'七牛云配置验证成功，使用 Bucket: {configured_bucket}')
        return True
        
    except Exception as e:
        current_app.logger.error(f'七牛云配置验证失败: {str(e)}')
        raise